package cn.uncode.springcloud.gateway.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import cn.uncode.springcloud.gateway.canary.CanaryStrategy;
import cn.uncode.springcloud.gateway.canary.DefaultCanaryStrategy;
import cn.uncode.springcloud.gateway.handler.RibbonCanaryRuleHandler;
import com.netflix.loadbalancer.ZoneAvoidanceRule;
import com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList;

/**
 * * 灰度路由初始化类
 * @author juny
 * @date 2019年1月24日
 *
 */
@Configuration
@ConditionalOnClass(DiscoveryEnabledNIWSServerList.class)
@AutoConfigureBefore(RibbonClientConfiguration.class)
@EnableConfigurationProperties({CanaryProperties.class})
public class RibbonCanaryAutoConfiguration {
	
	@Autowired
	private CanaryProperties canaryProperties;
	
	@Bean
	public CanaryStrategy canaryStrategy() {
		return new DefaultCanaryStrategy(canaryProperties);
	}

    @Bean
    @ConditionalOnMissingBean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public ZoneAvoidanceRule metadataAwareRule() {
        return new RibbonCanaryRuleHandler();
    }
}

